<template>
  <div class="search-div">
    <el-input
      style="width: 100%;"
      placeholder="搜索地点"
      class="search-input input-with-select"
      v-model="searchKey"
      clearable
      :trigger-on-focus="false"
      @input="changeSearchList()"
      @focus="focus"
      @clear="clear"
      @keyup.enter.native="searchKeyWord()"
    >
      <el-select
        v-model="value"
        slot="prepend"
        placeholder="中国"
        clearable
      >
        <div
          class="city-list"
          slot="empty"
        >

          <div
            class="city-list-item"
            v-for="item in cityList"
            :key="item.cityCode"
          >
            <div class="city">
              <el-link
                :underline="false"
                @click="selectCity(item)"
              >
                {{ item.nameabbrevation }}
              </el-link>
            </div>
            <div class="city-childs">
              <div
                v-for="ite in item.child"
                :key="ite.cityCode"
                class="city-childs-item"
              >
                <el-link
                  :underline="false"
                  @click="selectCity(ite)"
                >
                  {{ ite.nameabbrevation }}
                </el-link>
              </div>
            </div>
          </div>
        </div>
      </el-select>
      <el-button
        slot="append"
        icon="el-icon-search"
        @click="searchKeyWord()"
      ></el-button>
    </el-input>
    <div
      class="search-list"
      :style="{ height: listDivHeight + 'px' }"
      id="search-list"
      v-show="searchListVisiable"
    >
      <ul
        class="search-list-ul"
        v-if="hasSearchList"
      >
        <li
          v-for="item in searchList"
          :key="item.hotPointID"
        >
          <el-link
            :underline="false"
            @click="createMarker(item)"
          >
            <i class="el-icon-location-information"></i>
            {{ item.name }}
          </el-link>
          <br />
          <span style="font-size: 12px;vertical-align: bottom;">地址: {{ item.address }}</span>
          <el-divider></el-divider>
        </li>
      </ul>
      <span v-else>没有搜索到有关【{{ this.searchKey }}】的信息</span>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    map: {
      type: Object,
      default: null
    }
  },
  data () {
    return {
      searchKey: null,
      listDivHeight: window.innerHeight - 180,
      searchList: null,
      count: 10,
      searchListVisiable: false,
      hasSearchList: false, // 是否搜索到数据
      cityList: null,
      selectedCity: null,
      value: null,
      // specify: '156000000'
    }
  },
  methods: {
    // 下拉框清空事件
    clear () {
      this.selectedCity = null;
    },
    searchKeyWord () {

      if (this.searchKey && this.searchKey.length > 0) {
        this.hasSearchList = true;
        this.searchKeyStr();
      } else {
        // 搜索框没数据
        this.searchList = null;
        this.searchListVisiable = false;
        this.$emit('clearMarkers');
      }

    },
    selectCity (city) {
      this.selectedCity = city;
      this.value = city.nameabbrevation;
      console.log('选中：', this.selectedCity);
    },
    // 关键字搜索
    searchKeyStr () {
      let that = this;
      let specify = null;
      let queryType = 1;
      // if (this.selectedCity) {
      //   specify = this.selectedCity.cityCode;
      //   queryType = 12;
      // }
      $.ajax({
        url: '/tdt/v2/search',
        type: 'get',
        contentType: "application/json;charset=UTF-8", //指定消息请求类型
        data: {
          // 注意参数格式
          postStr: JSON.stringify({
            // 关键字
            "keyWord": that.searchKey,
            // "specify": specify,
            // 地图等级，需要设置整数
            "level": that.map.getView().getZoom(),
            // 地图范围
            // "mapBound": that.map.getView().calculateExtent(that.map.getSize()).toString(),
            "mapBound": "61.17968750000273,1.2443569119745916,149.07031250000273,53.90364326695567",
            // 查询类型
            "queryType": queryType,
            // 分页
            "start": '0',
            "count": '20',
          }),
          type: 'query',
          // 请更换自己的 tk，此 tk 只能在当前域名下使用
          tk: '9aa421bfac4b31f0ad91a7118973689d',
        },
        success: function (res, status) {

          console.log('搜索结果', res)
          that.searchList = res.pois;
          that.$emit('getResults', res.pois);
          if (that.searchList) {
            that.searchListVisiable = true;
            console.log(that.searchListVisiable)
            that.computeListDivHeight();
          } else {
            console.log('没有搜索到数据')
            that.hasSearchList = false;
            that.setListDivHeight('40px');
            that.searchListVisiable = true;
          }
        },
      });
    },
    // 地理编码查询
    /* searchName () {
      let that = this;
      $.ajax({
        url: '/tdt/geocoder',
        type: 'get',
        contentType: "application/json;charset=UTF-8", //指定消息请求类型
        data: {
          // 注意参数格式
          ds: JSON.stringify({
            // 关键字
            "keyWord": that.searchKey,
          }),
          type: 'query',
          // 请更换自己的 tk，此 tk 只能在当前域名下使用
          tk: '9aa421bfac4b31f0ad91a7118973689d',
        },
        success: function (res, status) {

          res = JSON.parse(res);
          console.log(res)
          that.$emit('handleGeocoder', res);
        },
        
      });
    }, */
    // 地理逆编码查询，根据坐标查询名称
    searchCoordinate () {

      // 清除上一次叠加对象
      // layerVector && layerVector.getSource().clear();

      let coordinates = $('#searchCoordinateQuery').val().split(',');

      $.ajax({
        url: 'http://api.tianditu.gov.cn/geocoder',
        type: 'get',
        contentType: "application/json;charset=UTF-8", //指定消息请求类型
        data: {
          // 注意参数格式
          postStr: JSON.stringify({
            // 坐标
            "lon": coordinates[0],
            "lat": coordinates[1],
            "ver": 1
          }),
          type: 'geocode',
          // 请更换自己的 tk，此 tk 只能在当前域名下使用
          tk: '9aa421bfac4b31f0ad91a7118973689d',
        },
        beforeSend: function () {
          layer.load(2, {
            shade: [0.5, '#fff'] //0.1透明度的白色背景
          })
        },
        success: function (res, status) {

          layer.closeAll();

          res = JSON.parse(res);

          res.result && addMarker(res.result);
        },
      });
    },

    // 行政区划，根据关键字查询行政区划信息；包括名称、类型（省市）、范围等
    searchGovernment (val) {

      let that = this;
      $.ajax({
        url: '/tdt/administrative',
        type: 'get',
        async: false,
        contentType: "application/json;charset=UTF-8", //指定消息请求类型
        data: {
          // 注意参数格式
          postStr: JSON.stringify({
            // 关键字
            "searchWord": val,
            "searchType": '0',
            // 子项
            "needSubInfo": 'false',
            // 所有属性
            "needAll": 'true',
            // 边界属性，好像是不起作用
            "needPolygon": 'true',
            "needPre": 'true',
          }),
          type: 'query',
          // 请更换自己的 tk，此 tk 只能在当前域名下使用
          tk: '9aa421bfac4b31f0ad91a7118973689d',
        },
        // 请求前处理事项
        beforeSend: function () {
        },
        success: function (res, status) {

          res = JSON.parse(res);
          that.$emit('handleGovernment', res.data);
          that.cityList = res.data.child.sort((city1, city2) => {
            return parseInt(city1.cityCode) - parseInt(city2.cityCode);
          });

          /* if (res && res.data && res.data.length > 0) {

            // 拼接通用方法参数
            let location = {};

            // 坐标
            location.lon = res.data[0].lnt;
            location.lat = res.data[0].lat;

            // 名称
            location.keyWord = res.data[0].name;

            // 四至范围
            location.bound = res.data[0].bound.split(',');

            // 类型（省市县）
            location.adminType = res.data[0].adminType;

            // 拼接矩形（面状图形要素）
            let polygon = 'POLYGON((' + location.bound[0] + ' ' + location.bound[1] + '' +
              ',' + location.bound[2] + ' ' + location.bound[1] + ',' +
              '' + location.bound[2] + ' ' + location.bound[3] + ',' +
              '' + location.bound[0] + ' ' + location.bound[3] + ',' +
              '' + location.bound[0] + ' ' + location.bound[1] + '))';

            location.polygon = polygon;

            res.data[0].location = location;

            addMarker(res.data[0]);
          } */
        },
      });
    },
    changeSearchList () {
      this.computeListDivHeight();
      this.searchKeyWord(this.select);
    },
    createMarker (item) {
      this.$emit('selectPoint', item);
      this.searchKey = item.name;
      this.searchListVisiable = false;
    },
    focus () {
      if (this.searchKey && this.searchKey.length > 0 && this.searchList) {
        this.searchListVisiable = true;
      }
    },
    computeListDivHeight () {
      var div = document.getElementById('search-list');
      if (div) {
        if (window.innerHeight > 240) {
          div.style.height = window.innerHeight - 180 + 'px';
          return;
        }
        div.style.height = '60px';
      }
    },
    setListDivHeight (val) {
      var div = document.getElementById('search-list');
      div.style.height = val;
    }

  },
  created () {
    this.$nextTick(() => {
    });
  },
  mounted () {
    window.onresize = () => {
      this.computeListDivHeight();
    }
  },
  beforeMount () {
    this.searchGovernment('156000000');
  },
  computed: {
  },
  watch: {
  }
}
</script>

<style lang="scss" scoped>
.search-div {
  position: relative;
  z-index: 999;
  width: 450px;
  top: 30px;
  left: 50px;
  opacity: 0.9;
}

.search-list {
  position: absolute;
  width: 100%;
  z-index: 999;
  background-color: white;
  line-height: 30px;
  overflow-y: auto;
  overflow-x: hidden;
}

.search-list > ul > li {
  list-style-type: none;
  padding-right: 20px;
}

.search-list > .search-list-ul {
  text-align: left;
  width: 340px;
  padding-left: 15px;

  a {
    text-decoration: none;
  }
}

.el-divider--horizontal {
  display: block;
  height: 1px;
  width: 100%;
  margin: 6px 0;
}

.search-div .el-select {
  width: 130px;
}

.city-list {
  height: 400px;
  width: 300px;
  overflow: auto;
  overflow-x: hidden;
  padding: 8px;
}

.city-list-item {
  width: 100%;
  display: flex;
}

.city {
  width: 40%;
  height: 100%;
}

.city-childs {
  width: 60%;
  height: 100%;
}

.city-childs-item {
  float: left;
  padding: 5px;

  a {
    text-decoration: none;
  }
}
</style>